
<template xmlns:el-col="http://www.w3.org/1999/html">
    <el-container>
        <el-header>
            <ul class="ul_li">
            <li>
            <span style="margin-left: 50px" @click="signOut">退出</span>
            </li>
            <li>
                <img :src="`http://127.0.0.1:8081/avatar/${avatar}`"
                     style="width: 21px;height: 21px;border-radius: 50%" v-show="pic">
            </li>
            </ul>
            <el-col :span="4">
                <el-icon size="25px" style="margin: 3px 0px 0px 20px">
                    <router-link to="/shopCar"><ShoppingCart/></router-link>
                </el-icon>
            </el-col>
        </el-header>
        <el-main>
            <div class="common-layout">
               <router-link to="/" style="text-decoration-line: none;color: black;margin-top: -10px"><h4>&lt;返回首页</h4></router-link>
                <el-container :model="product">
                    <div class="left">
                        <div class="left_1">
                        <el-image class="picture" :src="`http://127.0.0.1:8081/product/${product.picture}`"/>
                        </div>
                        <div class="left_2">
                            <el-image class="pictures" v-for="picture in pictures" :key=picture :src="`http://127.0.0.1:8081/product/`+`${picture}`"/>
                        </div>
                    </div>
                    <div class="right">
                        <h2 v-text="product.title"></h2>
                        <div id="info">
                            <span>原价:</span>
                            <span id="price" v-text="product.price" style="text-decoration-line: line-through"></span><br>
                            <span>现价:</span>
                            <span id="new_price"  v-text="product.new_price"></span>
                            <div id="description-wrapper">
                                <span id="item-description">描述</span>
                                <span id="description" v-text="product.description">
                        </span>
                                <div class="clear"></div>
                            </div>
                        </div>
                        <div style="margin-top: 35px;--el-border-color-hover: black" >
                            <el-input-number v-model="num" size="large" @change="handleChange(num)"/>
                        </div>
                        <div class="coupon" style="margin-top: 35px">
                            <el-button @click="thirty(couponForm1)">满300减30</el-button>
                            <el-button @click="fifty(couponForm2)">满500减50</el-button>
                        </div>
                        <div class="shop">
                            <el-button @click="pay()">立即购买</el-button>
                            <el-button style="background: #f5f3ef" @click="shopCars()">加入购物车</el-button>
                            <el-button @click="collect()"><span v-show="coll">取消</span>收藏</el-button>
                        </div>
                    </div>
                </el-container>
            </div>
        </el-main>
        <el-dialog v-model="order" title="加入订单" width="35%" center>
           地址： <el-select v-model="value" value-key="id" placeholder="Select">
                    <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.address"
                        :value="item"
                    ><span @click="selectA(item.id)">{{item.address}}</span></el-option>
            </el-select>
            <p>
                姓  名：{{ value ? value.name: 'no select' }}
                手机号：{{ value ? value.telephone: 'no select' }}
                地  址：{{ value ? value.address: 'no select' }}
            </p>
            <el-form :model="orderForm" label-width="80px">
                <el-form-item style="align-content: center">
                    <el-image style="height: 100px;width: 100px" :src="`http://127.0.0.1:8081/product/${orderForm.picture}`"/>
                </el-form-item>
                <el-form-item label="商品名称:">
                    {{orderForm.title}}
                </el-form-item>
                <el-form-item label="商品描述:">
                    {{orderForm.description}}
                </el-form-item>
                <el-form-item label="单价:">
                   {{orderForm.unit_price}}
                </el-form-item>
                <el-form-item label="数量:">
                    {{orderForm.number}}
                </el-form-item>
                <el-radio-group v-model="radio" class="ml-4">
                    <el-radio v-show="coupon1" label="1" size="large" @change="getRadio()">满300减30</el-radio>
                    <el-radio v-show="coupon2" label="0" size="large" @change="getRadio()">满500减50</el-radio>
                </el-radio-group>
                <el-form-item label="总价:">
                    {{orderForm.total}}
                </el-form-item>
                <el-button @click="cs()">确认订单</el-button>
            </el-form>
        </el-dialog>

        <el-dialog v-model="zf" title="支付订单" width="350px" center>
            <el-button @click="zf1()">确认支付</el-button>
            <el-button @click="qxzf()">取消支付</el-button>
        </el-dialog>

        <el-dialog v-model="jishi" title="未支付" width="35%">
            <div>
                <p>剩余时间{{count}}秒后自动取消订单</p>
            </div>
            <el-button @click="zf1()">确认支付</el-button>
        </el-dialog>

            <div v-for="item in comment" :key="item.id" style="background-color: #888888;margin-top: 50px;
                margin-left:450px;height: 10%;width: 55%">
                <div class="left" style="float: left;width: 5%">
                    <el-image class="picture" :src="`http://127.0.0.1:8081/avatar/${item.user.avatar}`" 
                    style="border-radius: 50%;height: 100px;width: 100px;margin:20px 0 0 20px"/>
                    <div style="margin: 5px 0 5px 50px;color: gold;font-size: 20px">{{item.user.username}}</div>
                </div>
                <div class="right" style="float: right;margin-right: 200px">
                    <div style="margin-top: 20px;height: 100px;background-color: white">{{item.textarea}}</div>
                    <div style="margin-top: 5px;color: orange;font-size: 20px">{{item.time}}</div>
                </div>
            </div>

    </el-container>
</template>
<script lang="ts" setup>
import axios from 'axios'
import {onMounted,reactive, ref, toRaw} from 'vue'
import {useRoute} from "vue-router";
import goodsApi from "../api/goods.js";
import cartApi from "../api/shopCarApi.js"
import userApi from "../api/userApi.js"
import historyApi from "../api/history.js"
import collectApi from "../api/collect.js"
import couponApi from "../api/coupon.js"
import router from '../router/index.js'
import addressApi from '../api/address.js'
import orderApi from '../api/order.js'
import commentApi from '../api/comment.js'

const num = ref(1)
const coll = ref()
if (localStorage.getItem('token1') == null) {
    coll.value = false
}
const orderForm = reactive({
    picture:'',
    title:'',
    description:'',
    unit_price:'',
    number:num,
    total:'',
    aid:''
})
console.log(typeof (orderForm.total))
const route = useRoute();
let productId = route.query.pid;
console.log(productId)
const product = ref([])
const pictures = ref([])

// #################################显示#####################################
const productShow = () =>{
    axios.get('http://127.0.0.1:8080/product/queryById/' + productId).then(res=>{
        product.value = res.data
        pictures.value = res.data.pictures.split(',');

        orderForm.picture = res.data.picture
        orderForm.title = res.data.title
        orderForm.description = res.data.description
        orderForm.unit_price = JSON.stringify(res.data.new_price)
        orderForm.total = JSON.stringify(res.data.new_price)
        console.log(orderForm.total)

        if(localStorage.getItem('token1')){
            axios.get('http://127.0.0.1:8080/collect/querySelect')
                .then(res =>{
                        if(res.data){
                            coll.value = true
                        }else{
                            coll.value = false
                        }
                    }
                )
        }
    }).catch(error=>{
        console.log(error)
    })
    if(localStorage.getItem('token1')){
        axios.get('http://127.0.0.1:8080/collect/querySelect')
            .then(res =>{
                    if(res.data){
                        coll.value = true
                    }
                }
            )
    }
}
const handleChange=(value)=>{
    console.log(value)
    orderForm.number = value
    console.log(orderForm.number)
    orderForm.total = JSON.stringify(orderForm.unit_price * value)
    console.log(orderForm.total)
}
const form =reactive({
    number:num
})

//  ################################加入购物################################
const shopCars = async () => {
        console.log("1111")
        if (localStorage.getItem('token1') == null) {
            alert("未登录，请先登录")
        }
        if (localStorage.getItem('token1')) {
            const res = await cartApi.create(form);
            if (res.data) {
                alert("加入成功");
            } else {
                alert("加入失败")
            }
        }
    }
const avatar = ref('')
const pic = ref(false)
console.log()
if(localStorage.getItem('token1')){
    let uid = ref('');
    const userToken = localStorage.getItem('token1');
    const payload = userToken.split('.')[1]
    const data = JSON.parse(decodeURIComponent(escape(window.atob(payload.replace(/-/g, "+").replace(/_/g, "/")))))
    uid = data.sub;
    axios.get('http://127.0.0.1:8080/user/queryById/' + uid)
        .then(res =>{
            pic.value = true;
            avatar.value = res.data.avatar;
        })
}
console.log(localStorage.getItem('token1'))

// #####################退出登录########################
const signOut = async () => {
    console.log(111)
    const res = await userApi.signOut()
    console.log(res.data)
    if (res.data) {
        localStorage.removeItem('token1')
        console.log(localStorage.getItem('token1'));
        router.push({
            path:'/'
        })
    } else {
        //
    }
}
// #####################加入足迹#########################
const history = async() =>{
    const res = await historyApi.create();
    if(res.data){
        console.log(res.data)
    }
}
// ########################加入收藏#############################
const collect = async() =>{
    if (localStorage.getItem('token1') == null) {
        alert("未登录，请先登录")
    }
    if (localStorage.getItem('token1')){
        const res1 = await collectApi.querySelect()
        if(res1.data){
            const res2 = await collectApi.removeCollect()
            if(res2.data){
                alert("是否取消收藏？")
                productShow()
            }
        }else {
            const res = await collectApi.create()
            if(res.data ){
                alert("收藏成功")
                productShow()
            }
        }
    }
}
onMounted(() => {
    productShow()
    addresses()
    couponT()
    commentShow()
})
if(localStorage.getItem('token1')){
    history()
}

const couponForm1 = reactive({
    amount:30,
    code:'满300减30'
})
const couponForm2 = reactive({
    amount:50,
    code:'满500减50'
})
// ################################领取优惠券###################################
const thirty = async(couponForm1) =>{
    if(localStorage.getItem('token1') == null){
        alert('未登录，请先登录')
    }else {
        const res = await couponApi.create(couponForm1)
        if(res.data){
            alert("领取成功")
        }
    }
}
// ##################################领取优惠券（满500减50）###################################
const fifty = async(couponForm2) =>{
    if(localStorage.getItem('token1') == null){
        alert('未登录，请先登录')
    }else {
        const res = await couponApi.create(couponForm2)
        if(res.data){
            alert("领取成功")
        }
    }
}
// ###########################加入订单################################
const order = ref(false)
// -----------------地址选择--------------------
type Option = {
    id: number
    name: string
    telephone: string
    address: string
}
const value = ref<Option>()
const options = ref([])
const addresses = async() =>{
    const res = await addressApi.queryByUid()
    options.value = res.data
}
const selectA = (aid) =>{
    orderForm.aid = JSON.stringify(aid)
    console.log(typeof (orderForm.aid))
}
// -------------优惠券选择-------------------
const coupon1 = ref(false)
const coupon2 = ref(false)
let tQ;
let fQ;
let tA;
let fA;
let tC;
let fC;

const radio = ref(
    '1'
);
const coupons = async() =>{
    const res = await couponApi.queryThirty()
    tQ = res.data.quantity
    tA = res.data.amount
    tC = res.data.code
    if(tQ && (orderForm.total > 300)){
        console.log(orderForm.total)
        coupon1.value = true
    }

    const res1 = await couponApi.queryFifty()
    fQ = res1.data.quantity
    fA = res1.data.amount
    fC = res1.data.code
    if(fQ && orderForm.total > 500){
        coupon1.value = true
        coupon2.value = true
    }
    if(radio.value == "1"){
        couponT()
    }
}
const couponT = () =>{
    if(tQ > 0 && orderForm.total > 300){
        couponForm3.code = tC
        console.log(couponForm3.code)
        let total = orderForm.total - tA
        orderForm.total = JSON.stringify(total)
        console.log(orderForm.total)
    }
}
const couponF = () =>{
    orderForm.total = JSON.stringify(orderForm.total - fA)
    console.log(orderForm.total)
}

const couponForm3 = reactive({
    code:null
})
const getRadio = () => {
    console.log(orderForm.total)
    radio.value
    console.log(radio.value)
    if(radio.value == "1"){
        couponForm3.code = tC
        console.log(couponForm3.code)
        let total = parseFloat(orderForm.total) + 50
        orderForm.total = JSON.stringify(total)
        couponT()
    }
    if (radio.value == "0"){
        couponForm3.code = fC
        console.log(couponForm3.code)
        orderForm.total = JSON.stringify(parseFloat(orderForm.total) + tA)
        couponF()
    }
}
// #####################点击出现订单框####################
const pay = async() =>{
    order.value = true
    coupons()
}
const zf = ref(false)
const cs = async() =>{
    // couponT()
    const res = await orderApi.create(orderForm)
    if(res.data){
        console.log("success")
        zf.value = true
        startTimer()
    }
}
const zf1 = async() =>{
    console.log(couponForm3.code)
    const res = await orderApi.modifySta1(couponForm3)
    if(res.data){
        zf.value = false
        order.value = false
        stopTimer()
        alert("支付成功")
    }
}
// #################取消支付####################
const jishi = ref(false)
const qxzf = () =>{
    zf.value = false
    order.value = false
    jishi.value = true
}
const count = ref(30);
let timer;

const startTimer = () => {
    timer = setInterval(() => {
        count.value--;
        if(count.value === 0){
            stopTimer()
            removeOrder()
        }
    }, 1000);

};
const stopTimer = () => {
    clearInterval(timer);
    jishi.value = false
    productShow()
};
const removeOrder = async () =>{
    const res = await orderApi.deleteOrder()
    if(res.data){
        alert("订单已取消")
    }
}

// #############################显示评价#########################
const comment = ref([])
const commentShow = async() =>{
    const res = await commentApi.queryByPid();
    if(res.data){
        comment.value = res.data
        console.log(comment.value)
    }
}

</script>
<style scoped>
.el-header{
    height: 50px;
    background-color: #545c64;
    position: relative;
}
.common-layout {
    width: 1080px;
    margin: auto;
    background: #fefefe;
    margin-top: -10px;
}

.left {
    width: 430px;
    margin-right: 40px;
}
.common-layout .left .left_1{
    width: 430px;
    height: 430px;
}
.left .left_2{
    width: 430px;
    margin-top: 20px;
}
.pictures {
    width: 100px;
    height: 90px;
}
.right {
    width: 620px;
}

.picture {
    width: 430px;
    height: 430px;
}
h2 {
    font-size: 20px;
    color: #333;
}

p {
    color: #999;
    margin: 10px 0 20px;
}

#info {
    background: #f5f3ef;
    border-top: 1px dotted #dedede;
    border-bottom: 1px dotted #dedede;
    padding: 20px 10px;
}

#price {
    color: red;
    font-size: 1.8em;
    margin-left: 35px;
    font-weight: bolder;
}

#price::before {
    content: '￥';
    font-size: .5em;
    color: red;
    font-weight: bolder;
}
#new_price {
    color: black;
    font-size: 1.8em;
    margin-left: 35px;
    font-weight: bolder;
}

#new_price::before {
    content: '￥';
    font-size: .5em;
    color: black;
    font-weight: bolder;
}
#item-description,
#description {
    display: inline-block;
    float: left;
}

#description {
    margin-left: 40px;
    width: 500px;
}
#description-wrapper {
    margin-top: 20px;
}

.clear {
    clear: both;
}

.shop {
    margin-top: 40px;
}

.shop .el-button {
    width: 160px;
    height: 80px;
}

.el-header .ul_li li {
    list-style: none;
    float: right;
    /*padding-left: 15px;*/
    padding-right:50px ;
    color: white;
    font-weight: bolder;
    font-size: 16px;
    cursor: pointer;
}

</style>